package cn.net.isir.controller.manager;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import cn.net.isir.common.ResultObject;
import cn.net.isir.core.BasicController;
import cn.net.isir.core.SetBasicService;
import cn.net.isir.entity.Table;
import cn.net.isir.service2.TableService;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.Map;

/**
 * @author liuxubo
 * @filename TableController.java
 * @package cn.net.isir.controller.manager
 * @email lxb@isir.net.cn
 * @date 2018/12/03
 * @comment
 * @since 1.8
 */
@RestController
@RequestMapping("/table")
public class TableController extends BasicController<Table> {
    @SetBasicService
    @Resource
    private TableService tableService;

    /**
     * 增加信息
     *
     * @param map 增加信息
     * @return 结果
     */
    @Override
    public ResultObject add(@RequestBody Map map) {
        Table table = JSONObject.parseObject(JSON.toJSONString(map), Table.class);
        Table exist = getExist(table.getTableNo(), table.getShopId());
        if (exist != null) {
            return new ResultObject(501, "table No. is already exist.", table.getTableNo());
        }
        return new ResultObject(200, "success", tableService.insert(table));
    }

    /**
     * 保存修改信息
     *
     * @param map 信息实体类
     * @return 结果
     */
    @Override
    public ResultObject edit(@RequestBody Map map) {
        Table table = JSONObject.parseObject(JSON.toJSONString(map), Table.class);
        Table exist = getExist(table.getTableNo(), table.getShopId());
        // 如果已经存在了
        if (exist != null) {
            // 并且不是本桌号
            if (!exist.getId().equals(table.getId())) {
                return new ResultObject(501, "table No. is already exist.", table.getTableNo());
            }
        }
        return super.edit(map);
    }

    /**
     * 根据店铺和桌号获取已存在的桌号
     *
     * @param tableNo 桌号
     * @param shopId  店铺
     * @return 已存在返回实体类，否则返回null
     */
    private Table getExist(String tableNo, String shopId) {
        //获取现有的桌号
        Table t = new Table();
        t.setTableNo(tableNo);
        t.setShopId(shopId);
        return tableService.selectOne(t);
    }
}
